package com.service.devimonitor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.bpms.common.CommonUtil;
import com.bpms.common.JdbcWorker;
import com.bpms.common.VO;
import com.bpms.eai.PackTool;
import com.bpms.esb.IService;
import com.service.util.DateUtil;
import com.zk.atm.forms.AtmpDeviceStatusForm;
import com.zk.atm.forms.AtmpDeviceTypeForm;
import com.zk.atm.utils.AccessDBConnection;
import com.zk.atm.utils.ConstantsAtmp;
import com.zk.atm.utils.PrimaryKeyUtil;
import com.zk.atm.utils.StringUtil;
import com.zk.atm.vo.AtmpDevice;

public class Atmpdeviceserviceimpl extends PackTool implements IService {
    public static Logger logger=Logger.getLogger(Atmpdeviceserviceimpl.class);
	@Override
	public VO exec(VO args) {
        
		VO vo=new VO();
		try{
			String m=args.getAttr("m");
			AtmpDeviceStatusForm form=(AtmpDeviceStatusForm) args.getObj(ConstantsAtmp.ATMP_DEVICE_FORM);
			/*if(m.equals(ConstantsAtmp.ATMP_DEVICE_ACTION_SAVE_METHOD)){
				boolean is_success=this.saveAtmpDevice(form);
				String msg="保存失败!";
				if(is_success==true){
					msg="保存成功!";
					vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET,"0");
				}
				vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE,msg);
				return vo;
			}
			else if(m.equals(ConstantsAtmp.ATMP_DEVICE_ACTION_DEL_METHOD)){
				String device_ip=form.getDevice_ip();
				boolean is_refer_status_current=this.checkDeviceReferStatusCurrent(form);
				VO msg_vo=new VO();
				if(is_refer_status_current==true){
					msg_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "当前IP为"+device_ip+"的设备,在设备状态表中有记录,不能执行删除操作!");
					return msg_vo;
				}
				
				boolean is_success=this.deleteDeviceByDeviceIp(form);
				if(is_success==true){
					msg_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
				}
				return msg_vo;
			}
			else if(m.equals(ConstantsAtmp.ATMP_DEVICE_CHECK_IP_ADDRESS_IS_ONLY_ONE)){
				AtmpDeviceStatusForm args_form=new AtmpDeviceStatusForm();
				this.checkDeviceIPIsExsitsInAtmpDevice(args_form);
			}
			CommonUtil.debug("devimonitor.AtmpDeviceServiceImpl success");*/
			return vo;
		}catch(Exception e){
			CommonUtil.debug("devimonitor.AtmpDeviceServiceImpl exception",e);
			return null;
		}
	}
	
	public VO saveOrUpdateAtmpDevice(AtmpDeviceStatusForm form) throws Exception{
		VO vo=null;
		AtmpDevice ad=form.getDevice_vo();
		String device_id=StringUtil.getPropertyValue(ad.getDevice_id());
		String table_name="atmp_device";
		if(device_id.equals("")){
			  ad.setIs_use("1");
			  ad.setIs_dump("0");
		}
		JdbcWorker jdbc=new JdbcWorker();
		//把device里面的值,全部封装到bpmvo中
		 vo=getAtmpVO(ad);
		String primary_column="device_id";
		//如果id为空,则表明是新增操作,则获取生成的主键,保存
		if(device_id.equals("")){
			String primary_key=PrimaryKeyUtil.getPrimaryKey(table_name, null);
			vo.setAttr(primary_column, primary_key);
		    vo.voType=table_name;
		    jdbc.insert(vo);
		    System.out.println("新增操作成功!");
		}else{
			VO key_vo=new VO();
			key_vo.setAttr(primary_column, ad.getDevice_id());
			key_vo.keyString=primary_column;
			key_vo.voType=table_name;
			jdbc.update(vo, key_vo);
			System.out.println("更新操作成功!");
		}
		return vo;
	}
	//动态存放设备类型的map
	//设备保存
	public boolean saveAtmpDevice(AtmpDeviceStatusForm form) throws Exception{
		boolean is_success=false;
		String device_id="";
		JdbcWorker jdbc=new JdbcWorker();
		try {
			AtmpDevice ad=form.getDevice_vo();
			device_id=StringUtil.getPropertyValue(ad.getDevice_id());
			String table_name="atmp_device";
			if(device_id.equals("")){
				  ad.setIs_use("1");
				  ad.setIs_dump("0");
			}
			//把device里面的值,全部封装到bpmvo中
			VO vo=getAtmpVO(ad);
			String primary_column="device_id";
			 Date d=new Date();
			 String date_value=DateUtil.getInstance().getDateFormat(d, "yyyy-MM-dd HH:ss:mm");
			//如果id为空,则表明是新增操作,则获取生成的主键,保存
			if(device_id.equals("")){
				String primary_key=PrimaryKeyUtil.getPrimaryKey(table_name, null);
				vo.setAttr(primary_column, primary_key);
			    vo.voType=table_name;
			    vo.setObj("create_date",date_value);
			    vo.setObj("update_date", date_value);
			    jdbc.insert(vo);
			    System.out.println("新增操作成功!");
			    is_success=true;
			}else{
				VO key_vo=new VO();
				key_vo.setAttr(primary_column, ad.getDevice_id());
				key_vo.keyString=primary_column;
				key_vo.voType=table_name;
				vo.setObj("update_date", date_value);
				jdbc.update(vo, key_vo);
				System.out.println("更新操作成功!");
				is_success=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			jdbc=null;
		}
		return is_success;
	}
	
	//把页面中的device的值,全部封装到bpmvo中,调用jdbcworker的insert,update方法执行插入或更新操作.
	protected VO getAtmpVO(AtmpDevice ad) throws Exception{
		VO vo=new VO();
		Field[] fields=ad.getClass().getDeclaredFields();
		 for (Field field : fields) {
				String field_name=field.getName();
				//System.out.println(field_name);
				String method_name=getGetterMethod(field_name);
				if(method_name.equals("")){		
					continue;
				}
				Method m=null;
				try {	
					m=ad.getClass().getMethod(method_name);		
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				if(m==null){
					continue;
				}
				String type_name=field.getType().getName().toString();
				Object value=null;
				if(type_name.equals("java.lang.String")){
					value=new String();
				    value=(String)m.invoke(ad);
				}else if(type_name.equals("java.lang.Long")){
					value=new Long(-1);
					value=m.invoke(ad);
				}else if(type_name.equals("java.util.Date")){
					value=new Date();
					value=m.invoke(ad);
				}else{
					value="";
				}
				if(value!=null){
					if(logger.isDebugEnabled()){
					  System.out.println("getAtmpVO:reflect:value="+value.toString());
					}
					vo.setObj(field_name, value);
				}
		  }
		 return vo;
	}
	
	public static void main(String[] args) {
		Atmpdeviceserviceimpl service=new Atmpdeviceserviceimpl();
		AtmpDeviceStatusForm form=new AtmpDeviceStatusForm();
		AtmpDevice device=new AtmpDevice();
		device.setDevice_id("7");
		device.setProvider_name("北京中科金财科技股份有限公司");
		device.setDevice_code("SZ_KS_0001");
		device.setDevice_ip("192.168.1.6");
		//device.setUpdate_date(new java.sql.Date());
		device.setDevice_name("苏州分行-昆山南区支行");
		form.setDevice_vo(device);
		try {
			boolean is_ok=service.saveAtmpDevice(form);
		//boolean is_ok=	service.deleteDeviceByDeviceIp(form);
		//boolean is_ok=	checkDeviceReferStatusCurrent(form);
		System.out.println("is_ok="+is_ok);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected static String getGetterMethod(String column_name) throws Exception{
		String getter_method="get";
		column_name=column_name.substring(0,1).toUpperCase()+column_name.substring(1,column_name.length());
		getter_method+=column_name;
		if(logger.isDebugEnabled()){
		  System.out.println("getter_method="+getter_method);
		}
		return getter_method;
	}

	public boolean executeSaveOrDelBySql(AtmpDeviceStatusForm statusForm) throws Exception{
		boolean is_success=false;
		String sql=StringUtil.getPropertyValue(statusForm.getExec_sql());
		if(sql.equals("")){
			return is_success;
		}
		Connection conn=null;
		try {
			conn=AccessDBConnection.getConnection();
			PreparedStatement pst=conn.prepareStatement(sql);
			pst.execute(sql);
			is_success=true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return is_success;
	}

	public static boolean  checkDeviceReferStatusCurrent(AtmpDeviceStatusForm statusForm)throws Exception {
		String sql="    select count(*) as total from atmp_device ad ,atmp_device_status_current adsc  " +
		" where ad.device_ip=adsc.deviceip " +
		" and (ad.device_ip=? or ad.device_id=?)";
		String device_ip=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_ip());
		String device_id=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_id());
		if(device_ip.equals("")){
			return false;
		}
		List list=new ArrayList();
		Connection conn=null;
		try {
			conn=AccessDBConnection.getConnection();
			PreparedStatement pst=conn.prepareStatement(sql);
			pst.setString(1, device_ip);
			pst.setString(2, device_id);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				String total=rs.getString("total");
				list.add(total);
			}
			if(list.size()>0){
				Integer number=new Integer(list.get(0).toString());
				return number>0?true:false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return false;
	}

	public boolean deleteDeviceByDeviceIp(AtmpDeviceStatusForm statusForm) throws Exception {
		String device_ip=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_ip());
		String device_id=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_id());
		if(device_ip.equals("")&&device_id.equals("")){
			String msg="参数值:device_ip为空,不能执行删除操作!";
			System.out.println(msg);
			logger.error("deleteDeviceByDeviceIp:"+msg);
			return false;
		}
		String exec_sql="  delete from atmp_device ad  where 1=1 " +
				" and (ad.device_ip='"+device_ip+"' or ad.device_id='"+device_id+"' )";
		statusForm.setExec_sql(exec_sql);
		return this.executeSaveOrDelBySql(statusForm);
	}
	/**
	 * @author zengqun
	 * @remark 检查atmp_device表中有无重复的ip地址,如果有,则不允许保存;
	 *         如果大于1,则表明有重复的IP地址;
	 * @param statusForm
	 * @return
	 * @throws Exception
	 */
	public static boolean  checkDeviceIPIsExsitsInAtmpDevice(AtmpDeviceStatusForm statusForm)throws Exception {
		String sql="      select count(*) as total from atmp_device ad where ad.device_ip=?";
		String device_ip=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_ip());
		String device_id=StringUtil.getPropertyValue(statusForm.getDevice_vo().getDevice_id());
//		int check_number_add=0;//新增时,保证IP没有被占用;即校验是否大于0
//		int check_number_update=1;//修改时,保证IP有且只有1条;即校验变更后的ip是否存在大于1条的情况
//		int check_number=device_id.equals("")?check_number_add:check_number_update;
		if(device_ip.equals("")){
			return false;
		}
		List list=new ArrayList();
		Connection conn=null;
		try {
			conn=AccessDBConnection.getConnection();
			PreparedStatement pst=conn.prepareStatement(sql);
			pst.setString(1, device_ip);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				String total=rs.getString("total");
				list.add(total);
			}
			if(list.size()>0){
				Integer number=new Integer(list.get(0).toString());
				return number>0?true:false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return false;
	}

}